import java.util.LinkedList;

import dao.TestReflect;
import javassist.expr.NewArray;

public class MyLinkList {

	private Link start;
	private Link end;
	private int size;
	
	
	public void print() {
		for(Link link=start;link!=null;link=link.getNext()) {
			System.out.println(link.getData());
		}
		if (size!=0) {
			System.out.println("第一个元素："+start.getData());
			System.out.println("最后一个元素："+end.getData());
		}else {
			System.out.println("链表为空");
		}
		System.out.println("链表大小："+size);
		
	}

	public <T> void add(T t) {
		Link link = new Link();
		link.setData(t);
		link.setNext(null);

		if (size == 0) {
			start = link;
			end = link;
			link.setLast(null);
		} else {
			link.setLast(end);
			end.setNext(link);
			end = link;
		}
		size++;
	}

	public <T> void remove(T t) {
		if (0 == size) {
			return;
		} else {
			Link current = start;
			while (null != current) {
				if (current.getData() == t) {
					Link currentlast = current.getLast();
					Link currentnext = current.getNext();
					if(null==currentlast) {
						//是第一个元素
						currentnext.setLast(null);
						start=currentnext;
					}else if(null==currentnext){
						//最后一个元素
						currentlast.setNext(currentnext);
						end=currentlast;
					}else {
						currentlast.setNext(currentnext);
					}
					size--;
					return;
				} else {
					current = current.getNext();
				}
			}
		}
	}

	public void remove(int index) {
		// 删除第一位元素
		if (index == 0) {
			Link firstnext = start.getNext();

			if (null != firstnext) {
				// 如果不只一个元素
				firstnext.setLast(null);// 释放掉第一个元素
				start = firstnext;
			} else {
				// 如果只有一个元素
				start = null;
				end = null;
			}
		}
		// 不是删除第一个元素
		else {
			int i = 0;
			Link link = start;
			while (i < index) {
				i++;
				link = link.getNext();
			}
			if (null != link) {
				// index 元素存在
				Link linklast = link.getLast();
				Link linknext = link.getNext();
				linklast.setNext(linknext);
				// 是末尾元素
				if (link == end) {
					end = linklast;
				}
			}
		}
		size--;
	}
	
	public static void main(String[] args) {
		MyLinkList myLinkList =new MyLinkList();
		myLinkList.add("1");
		myLinkList.add("2");
		myLinkList.add("3");
		myLinkList.add("4");
		myLinkList.add("5");
		
		myLinkList.remove(3);
//		myLinkList.remove("5");
		
		myLinkList.print();
		
		LinkedList list=new LinkedList<String>();
		
		LinkedList linkedList =new LinkedList();
		
		linkedList.add(new TestReflect());
		
	}

}

class Link<T> {
	private Link last;
	private Link next;
	private T data;

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public Link getLast() {
		return last;
	}

	public void setLast(Link last) {
		this.last = last;
	}

	public Link getNext() {
		return next;
	}

	public void setNext(Link next) {
		this.next = next;
	}

}
